package net.qhzw.vip.qiyu.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import net.qhzw.vip.qiyu.entity.DtsUser;
import net.qhzw.vip.qiyu.feign.OAuth2FeignClient;
import net.qhzw.vip.qiyu.handler.ApiException;
import net.qhzw.vip.qiyu.handler.MyException;
import net.qhzw.vip.qiyu.model.LoginResult;
import net.qhzw.vip.qiyu.model.WxLoginInfo;
import net.qhzw.vip.qiyu.service.DtsUserService;
import net.qhzw.vip.qiyu.service.OauthLoginService;
import net.qhzw.vip.qiyu.service.WxAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WxAuthServiceImpl implements WxAuthService {

    @Autowired
    private WxMaService wxService;

    @Autowired
    private DtsUserService dtsUserService;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Value("${jwt.expiration}")
    private Long expiration;


    /*@Autowired
    private JwtTokenUtil jwtTokenUtil;*/

    @Autowired
    private OauthLoginService oauthLoginService;

    @Autowired
    private OAuth2FeignClient oAuth2FeignClient;

    @Override
    public LoginResult loginByWeixin(WxLoginInfo wxLoginInfo, HttpServletRequest request) {
        //log.info("【请求开始】微信登录,请求参数,wxLoginInfo:{}", JSONObject.toJSONString(wxLoginInfo));
        String code = wxLoginInfo.getCode();
        String sessionKey = null;
        String openId = null;
//        try {
//            WxMaJscode2SessionResult result = this.wxService.getUserService().getSessionInfo(code);
//            sessionKey = result.getSessionKey();
//            openId = result.getOpenid();
//        } catch (WxErrorException e) {
//            e.printStackTrace();
//            log.error("err: " + e.getMessage());
//        }
//        if (sessionKey == null || openId == null) {
//            log.error("微信登录,调用官方接口失败：{}", code);
//            throw new MyException(500, "微信登录,调用官方接口失败");
//        }
        openId = oAuth2FeignClient.getOpenId(code);
        if (StringUtils.isEmpty(openId)){
            throw new ApiException("调用微信openId失败，稍后重试！");
        }
        if (StringUtils.isEmpty(openId)) {
            throw new ApiException("微信登录,调用官方接口失败");
        }
        DtsUser user = dtsUserService.getOne(new LambdaQueryWrapper<DtsUser>()
                .eq(DtsUser::getWeixinOpenid, openId));
        if (user != null && 0 == user.getStatus()) {
            throw new MyException(500, "您的账号已被禁用请联系管理员!");
        }
        if (user == null) {
            user = new DtsUser();
            user.setId(IdWorker.getId());
            user.setUsername(openId);
            user.setPassword(new BCryptPasswordEncoder().encode(openId));
            user.setWeixinOpenid(openId);
            user.setAvatar(wxLoginInfo.getAvatarUrl());
            user.setNickname(wxLoginInfo.getNickName());
            user.setGender(wxLoginInfo.getGender());
            user.setUserLevel((byte) 0);
            user.setStatus((byte) 1);
            //user.setShareUserId(shareUserId);
            user.setUserRegtime(new Date());
            dtsUserService.save(user);
        } else {
            dtsUserService.updateById(user);
        }
        LoginResult login = oauthLoginService.login(String.valueOf(user.getId()), user.getUsername(), "weixin_type");
        //log.info("后台系统登录成功, 结果为:【{}】", JSON.toJSONString(login));
        return login;
    }


//    @Override
//    public LoginResult loginByWeixin(WxLoginInfo wxLoginInfo, HttpServletRequest request) {
//        log.info("【请求开始】微信登录,请求参数,wxLoginInfo:{}", JSONObject.toJSONString(wxLoginInfo));
//        String code = wxLoginInfo.getCode();
//        String sessionKey = null;
//        String openId = null;
//        try {
//            WxMaJscode2SessionResult result = this.wxService.getUserService().getSessionInfo(code);
//            sessionKey = result.getSessionKey();
//            openId = result.getOpenid();
//        } catch (WxErrorException e) {
//            e.printStackTrace();
//            log.error("err: " + e.getMessage());
//        }
//        if (sessionKey == null || openId == null) {
//            log.error("微信登录,调用官方接口失败：{}", code);
//            throw new MyException(500, "微信登录,调用官方接口失败");
//        }
//        DtsUser user = dtsUserService.getOne(new LambdaQueryWrapper<DtsUser>()
//                .eq(DtsUser::getWeixinOpenid, openId));
//        if (user != null && 0 == user.getStatus()) {
//            throw new MyException(500, "您的账号已被禁用请联系管理员!");
//        }
//        if (user == null) {
//            user = new DtsUser();
//            user.setId(IdWorker.getId());
//            user.setUsername(openId);
//            user.setPassword(new BCryptPasswordEncoder().encode(openId));
//            user.setWeixinOpenid(openId);
//            user.setAvatar(wxLoginInfo.getAvatarUrl());
//            user.setNickname(wxLoginInfo.getNickName());
//            user.setGender(wxLoginInfo.getGender());
//            user.setUserLevel((byte) 0);
//            user.setStatus((byte) 1);
//            //user.setShareUserId(shareUserId);
//            user.setUserRegtime(new Date());
//            dtsUserService.save(user);
//        } else {
//            dtsUserService.updateById(user);
//        }
//        LoginResult login = oauthLoginService.login(String.valueOf(user.getId()), user.getUsername(), "weixin_type");
//        log.info("后台系统登录成功, 结果为:【{}】", JSON.toJSONString(login, true));
//        return login;
//    }

    /***
     *查询这个用户对应的权限
     * 通过用户的id 查询用户的权限
     * @return
     */
    private Collection<? extends GrantedAuthority> getSysUserPermissions() {
        try {

            List<String> permissions = Arrays.asList("query"); // 权限的名称
            if (permissions == null || permissions.isEmpty()) {
                return Collections.emptySet();
            }
            return permissions.stream()
                    .map(perm -> new SimpleGrantedAuthority(perm))
                    .collect(Collectors.toSet());
        } catch (Exception e) {
            return null;
        }

    }

}
